package com.west.xu.gateway.filter;

import com.google.gson.GsonBuilder;
import com.tencent.tsf.gateway.core.annotation.TsfGatewayFilter;
import com.tencent.tsf.gateway.scg.AbstractTsfGlobalFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@TsfGatewayFilter
public class GatewayTokenFilter extends AbstractTsfGlobalFilter {
    private static final Logger logger = LoggerFactory.getLogger(GatewayTokenFilter.class);

    private static final String HEADER_TOKEN = "HEADER_TOKEN";

    @Override
    public int getOrder() {
        return -100;
    }

    @Override
    public boolean shouldFilter(ServerWebExchange exchange, GatewayFilterChain chain) {
        return true;
    }

    @Override
    public Mono<Void> doFilter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String token = exchange.getRequest().getHeaders().getFirst(HEADER_TOKEN);
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        if (token == null || token.isEmpty()) {
            logger.error(request.getURI().getRawPath() + ": Error [{}]", "token is empty");
//            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
//            return exchange.getResponse().setComplete();

            Map message = new HashMap();
            message.put("code", 0);
            message.put("message", "鉴权失败，无token");
            byte[] bits = new GsonBuilder().create().toJson(message).getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(bits);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.getHeaders().add("Content-Type", "text/json;charset=UTF-8");
            return response.writeWith(Mono.just(buffer));
        }
        return chain.filter(exchange);
    }


}
